<template>
  <div>
    <div class="select-box">
      <el-form :inline="true" :model="data.selectData" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="data.selectData.title" placeholder="请输入关键字" clearable />
        </el-form-item>
        <el-form-item label="详情">
          <el-input v-model="data.selectData.introduce" placeholder="请输入关键字" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="dataList.comList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="introduce" label="详情" />
    </el-table>
    <el-pagination
      @current-change="currentChange"
      @size-change="sizeChange"
      layout="prev, pager, next"
      :total="data.selectData.count * 2"
    />
  </div>
</template>

<script setup lang="ts">
import { getGoodsList } from '../request/api'
import { onMounted, reactive, computed, watch } from 'vue'
import { InitData, type ListInt } from '../type/goods'

const data = reactive(new InitData())

const getGoods = () => {
    getGoodsList()
      .then((res) => {
        data.list = res.data
        data.selectData.count = res.data.length
      })
      .catch(() => {
        console.log('error submit!')
      })
}

const onSubmit = () => {
  console.log(data.selectData)
  let arr: ListInt[] = [] // 定义数组，用来接受查询过后的数据
  if (data.selectData.title || data.selectData.introduce) {
    // 判断是否其中一个有值
    if (data.selectData.title) {
      arr = data.list.filter((value) => {
        return value.title.indexOf(data.selectData.title) !== -1
      })
    }
    if (data.selectData.introduce) {
      arr = data.list.filter((value) => {
        return value.introduce.indexOf(data.selectData.introduce) !== -1
      })
    }
  } else {
    arr = data.list
  }
  data.selectData.count = arr.length
  data.list = arr
}

watch([() => data.selectData.title, () => data.selectData.introduce], () => {
  if (data.selectData.title == '' && data.selectData.introduce == '') {
    getGoods();
  }
})

const currentChange = (page: number) => {
  data.selectData.page = page
}

const sizeChange = (pagesize: number) => {
  data.selectData.pagesize = pagesize
}

const dataList = reactive({
  comList: computed(() => {
    return data.list.slice(
      (data.selectData.page - 1) * data.selectData.pagesize,
      data.selectData.page * data.selectData.pagesize
    )
  })
})
onMounted(() => {
    getGoods();
})
</script>
